<template>
  <div class="vi-draggable">
    <slot />
  </div>
</template>

<script setup>
import Sortable from './Sortable'
import { defineEmits, defineProps, onMounted, getCurrentInstance } from 'vue'

// const emits = defineEmits([])
const props = defineProps({
  options: Object,
  list: Array
})

let sortable
const { ctx } = getCurrentInstance()
const defaultOptions = {
  group: {
    name: 'canvas',
    pull: 'clone',
    put: true
  },
  fallbackOnBody: true,
  emptyInsertThreshold: 0,
  sort: true,
  animation: 150,
  supportPointer: true,
  handle: '.vi-draggable',
  ghostClass: 'ghost-css',
  chosenClass: 'chosen-css'
}
const defineOptionsEvents = {
  onUpdate: () => {
    console.log('onUpdate', sortable.toArray())
  },
  onAdd: () => {
    console.log('onAdd', sortable.toArray())
  },
  onRemove: () => {
    console.log('onRemove', sortable.toArray())
  },
  onEnd: () => {
    console.log('onEnd', sortable.toArray())
    // document.dispatchEvent(new DragEvent('dragend'))
  }
}

/**
 * 拖拽注册
 */
function initOptions () {
  // 初始拖拽配置参数
  let options = Object.assign(defaultOptions, props.options)
  if (options?.sort) {
    options = {
      ...options,
      ...defineOptionsEvents
    }
  }
  // 获取当前实例对象
  sortable = new Sortable(ctx.$el, options)
}

function initDomDataId () {
  ctx.$el.children.forEach((dom, index) => {
    dom.dataset.id = props.list[index]
  })
}

onMounted(() => {
  initOptions()
  initDomDataId()
  console.log()
})
</script>

<style scoped lang="less">
.vi-draggable {
    width: 100%;
}
/deep/.ghost-css {
  position: relative;
  display: block;
  overflow: hidden ;
  width: 100% ;
  height: 2px ;
  padding: 0;
  // background-color: rgb(15,112,253);
  border: none;
  margin: 0;
  &::before {
    content: "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    height: 2px;
    width: 100%;
    z-index: 11;
    background-color: rgb(15,112,253);
  }
}
&.height-full {
  height: 100%;
}
</style>
